

--@ enable=true
--@ module=true
local json = require("json")
local persist = require("persist-table")
local argparse = require("argparse")
local repeatutil = require("repeat-util")

local GLOBAL_KEY = "autotest"

enabled = enabled or false
data = data or {

}



local function writeFile (str, ftype, filename) 
    file = io.open("./hack/raw/"..(filename or "tmp"), ftype)  -- w+ a
    file:write(str)
    file:close()
end

local function persist_state()
    persist.GlobalTable[GLOBAL_KEY] = json.encode({
        enabled=enabled,
        data=data
    })
end

--- Load the saved state of the script
local function load_state()
    -- load persistent data
    local persisted_data = json.decode(persist.GlobalTable[GLOBAL_KEY] or "") or {}
    enabled = persisted_data.enabled or enabled
    data = persisted_data.data or data
end

function set_data(val)
    data = val
    persist_state()
end

--- The main event loop of the script.
function event_loop()
    local date = os.date("%Y-%m-%d %H:%M:%S")

    writeFile(GLOBAL_KEY..":"..tostring(enabled).." "..date.."\n", "a", GLOBAL_KEY)
    if not enabled then return end

    -- persist_state()
    repeatutil.scheduleUnlessAlreadyScheduled(GLOBAL_KEY, 1, "days", event_loop)
end

--- Handles automatic loading
dfhack.onStateChange[GLOBAL_KEY] = function(sc)
    -- unload with game
    if sc == SC_MAP_UNLOADED then
        enabled = false
        return
    end

    if sc ~= SC_MAP_LOADED or df.global.gamemode ~= df.game_mode.DWARF then
        return
    end

    load_state()

    -- run the main code
    writeFile(GLOBAL_KEY..":onStateChange\n", "a", GLOBAL_KEY)
    event_loop()
end


if dfhack_flags.module then
    return
end

if df.global.gamemode ~= df.game_mode.DWARF or not dfhack.isMapLoaded() then
    dfhack.printerr("auto script needs a loaded fortress to work")
    return
end

load_state()
local args = {...}
if dfhack_flags and dfhack_flags.enable then
    args = {dfhack_flags.enable_state and 'enable' or 'disable'}
end

if args[1] == "enable" then
    enabled = true
elseif args[1] == "disable" then
    enabled = false
    persist_state()
    repeatutil.cancel(GLOBAL_KEY)
    return
else
    return
end

event_loop()
persist_state()
